# Create your views here.
from django.http import HttpResponse
import json
import logging
from jboss_memory_analyzer.analyzer.models import Jboss_Instance, Report

logger = logging.getLogger(__name__)
jboss_instances = {}

def load_main(request):
    
    data_map={}
    for i in jboss_instances.iterkeys():
        j_inst=Jboss_Instance.objects.get(id=jboss_instances[i].pk)
        reports=Report.objects.filter(jboss_instance=j_inst)
        
        dataset={"1":{'label':"Code Cache","data":[]},"2":{'label':"Code Cache Max","data":[]},"3":{'label':"Eden Space","data":[]},"4":{'label':"Eden Space Max","data":[]},"5":{'label':"Survivor Space","data":[]},"6":{'label':"Survivor Space Max","data":[]},"7":{'label':"Old Gen Space","data":[]},"8":{'label':"Old Gen Space Max","data":[]},"9":{'label':"Perm Gen Space","data":[]},"10":{'label':"Perm Gen Space Max","data":[]}}
        
        for j in xrange(0,len(reports)):
            rep=reports[j]        
            dt=float(rep.report_date)*1000
            dataset["1"]["data"].append([dt,rep.mem_cur_1])
            dataset["2"]["data"].append([dt,rep.mem_max_1])
            dataset["3"]["data"].append([dt,rep.mem_cur_2])
            dataset["4"]["data"].append([dt,rep.mem_max_2])
            dataset["5"]["data"].append([dt,rep.mem_cur_3])
            dataset["6"]["data"].append([dt,rep.mem_max_3])
            dataset["7"]["data"].append([dt,rep.mem_cur_4])
            dataset["8"]["data"].append([dt,rep.mem_max_4])
            dataset["9"]["data"].append([dt,rep.mem_cur_5])
            dataset["10"]["data"].append([dt,rep.mem_max_5])
        
        data_map[jboss_instances[i].pk]={"dataset":dataset,"instance":{"id":j_inst.pk,"name":j_inst.name}}
    
    result={}
    result["data"]=data_map
    result["settings"]={"1":["Code Cache"],"2":["Code Cache Max"],"3":["Eden Space"],"4":["Eden Space Max"],"5":["Survivor Space"],"6":["Survivor Space Max"],"7":["Old Gen Space"],"8":["Old Gen Space Max"],"9":["Perm Gen Space"],"10":["Perm Gen Space Max"]}         
    return HttpResponse(json.dumps(result))

def delete_reports(request):
    instanceId=request.POST.get('instanceId') 
    j_inst=Jboss_Instance.objects.get(id=instanceId)
    Report.objects.filter(jboss_instance=j_inst).delete()
    return HttpResponse(json.dumps("OK"))

def export_reports(request):
    import csv
    from datetime import datetime as dt
    # Create the HttpResponse object with the appropriate CSV header.
    instanceId=request.GET.get('instanceId') 
    j_inst=Jboss_Instance.objects.get(id=instanceId)
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename='+j_inst.name+'.csv'
    
    writer = csv.writer(response)
    
    writer.writerow(["Date","Code Cache","Code Cache Max","Eden Space","Eden Space Max","Survivor Space","Survivor Space Max","Old Gen Space","Old Gen Space Max","Perm Gen Space","Perm Gen Space Max"])
    reports=Report.objects.filter(jboss_instance=j_inst)
    for j in xrange(0,len(reports)):
            rep=reports[j]
            t = dt.fromtimestamp(float(rep.report_date))
            writer.writerow([t.strftime('%Y-%m-%d %H:%M:%S'),rep.mem_cur_1,rep.mem_max_1,rep.mem_cur_2,rep.mem_max_2,rep.mem_cur_3,rep.mem_max_3,rep.mem_cur_4,rep.mem_max_4,rep.mem_cur_5,rep.mem_max_5])

    return response
